package cn.itlaobing.springmvc.service;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itlaobing.springmvc.dao.AccountMapper;
import cn.itlaobing.springmvc.entity.Account;

@Service
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountMapper accountMapper;
	private String defaultPassword = "123456";

	// 创建帐号
	@Override
	public Account create(String account) {
		// 产生盐值 随机的16 数字与字母混合
		String salt = RandomStringUtils.random(16, true, true);
		// 密文
		String passwordDigest = crypt(defaultPassword, salt);
		Account acc = new Account();
		acc.setAccount(account);
		acc.setPasswordDigest(passwordDigest);
		acc.setSalt(salt);
		accountMapper.insertSelective(acc);
		return acc;
	}

	/**
	 * 加密
	 * @return
	 */
	private String crypt(String password, String salt) {
		// 对原始密码加密
		String passwordCrypt = DigestUtils.md5Hex(password + salt);
		//倒叙
		return StringUtils.reverse(passwordCrypt);
	}
	
	//登录
	@Override
	public Account validate(String account, String password) {
		Account acc = accountMapper.selectByAccount(account);
		if (acc == null) {// 找不到账号，返回null
			return acc;
		}
		// 验证密码(重新加密)
		String passwordDigest = crypt(password, acc.getSalt());
		// 数据库里的密码
		String realPasswordDigest = acc.getPasswordDigest();
		// 判断数据库中的密码  与 重新加密的密码是否 相同
		if (passwordDigest.equals(realPasswordDigest)) {
			return acc;
		}
		return null;
	}

	//更新最后一次登录时间
	@Override
	public void updateLastSignInDateTime(String account) {
		Account acc = accountMapper.selectByAccount(account);
		if(acc!=null){
			acc.setLastSignin(new Date());
			accountMapper.updateByPrimaryKeySelective(acc);
		}
	}

}
